package com.wuhunyu.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.wuhunyu.client.ServiceEduClient;
import com.wuhunyu.client.ServiceUserClient;
import com.wuhunyu.commonutils.check.Check;
import com.wuhunyu.commonutils.jwt.JwtUtils;
import com.wuhunyu.commonutils.result.CommonResult;
import com.wuhunyu.entities.Order;
import com.wuhunyu.mapper.OrderMapper;
import com.wuhunyu.query.OrderQuery;
import com.wuhunyu.service.OrderService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.wuhunyu.servicebase.exception.Assert;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.math.BigDecimal;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.UUID;

/**
 * <p>
 * 订单 服务实现类
 * </p>
 *
 * @author wuhunyu
 * @since 2021-01-26
 */
@Service("orderService")
public class OrderServiceImpl extends ServiceImpl<OrderMapper, Order> implements OrderService {

    @Autowired
    private ServiceEduClient serviceEduClient;

    @Autowired
    private ServiceUserClient serviceUserClient;

    @Resource
    private OrderMapper orderMapper;

    @Override
    @Transactional(rollbackFor = Exception.class)
    public CommonResult createOrder(String courseId, HttpServletRequest request) {
        // 参数校验
        Assert.isRight(Check.isBlank(courseId), "课程id不能为空");
        // 获取用户id
        String userId = JwtUtils.getMemberIdByJwtToken(request);
        Assert.isRight(Check.isBlank(userId), "用户尚未登录");
        // 获取课程信息
        Map<String, Object> course = serviceEduClient.selectCourseForOrder(courseId).getData();
        Assert.isRight(Check.isBlank(course), "课程信息查询失败");
        // 获取用户信息
        Map<String, Object> user = (Map<String, Object>) serviceUserClient.selectMemberInfo(userId).getData().get("info");
        Assert.isRight(Check.isBlank(user), "用户信息查询失败");
        // 构造订单对象
        Order order = new Order(
                null,
                UUID.randomUUID().toString().replaceAll("-", ""),
                (String) course.get("courseId"),
                (String) course.get("courseTitle"),
                (String) course.get("courseCover"),
                (String) course.get("teacherName"),
                (String) user.get("id"),
                (String) user.get("nickname"),
                (String) user.get("email"),
                new BigDecimal((double) course.get("price")),
                // 默认为微信支付
                1,
                0,
                null,
                null,
                null
        );
        // 执行插入操作
        Assert.isRight(orderMapper.insert(order) != 1, "订单新增失败");
        // 返回订单id
        Map<String, Object> map = new HashMap<>(16);
        map.put("orderNo", order.getOrderNo());
        return CommonResult.success("订单新增成功", map);
    }

    @Override
    public CommonResult selectOrderInfo(String orderNo) {
        // 校验参数
        Assert.isRight(Check.isBlank(orderNo), "订单编号不能为空");
        QueryWrapper<Order> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("order_no", orderNo);
        List<Order> orders = orderMapper.selectList(queryWrapper);
        Assert.isRight(orders == null || orders.size() == 0, "订单信息查询失败");
        // 封装结果集
        Map<String, Object> map = new HashMap<>(16);
        map.put("order", orders.get(0));
        return CommonResult.success("订单信息查询成功", map);
    }

    @Override
    public CommonResult selectOrderStatus(String courseId, HttpServletRequest request) {
        // 校验参数
        Assert.isRight(Check.isBlank(request), "request参数不能为空");
        // 获取用户id
        String userId = JwtUtils.getMemberIdByJwtToken(request);
        return this.selectOrderStatus(courseId, userId);
    }

    @Override
    public CommonResult selectOrderStatus(String courseId, String memberId) {
        System.out.println(courseId + "/" + memberId);
        // 校验参数
        Assert.isRight(Check.isBlank(courseId), "课程id不能为空");
        Assert.isRight(Check.isBlank(memberId), "用户未登录");
        // 校验用户是否存在
        Assert.isRight(Check.isBlank(serviceUserClient.selectMemberInfo(memberId)), "登录用户不存在");
        // 校验课程是否存在
        Assert.isRight(200 != serviceEduClient.isCourse(courseId).getCode(), "课程不存在");
        // 查询用户支付状态
        QueryWrapper<Order> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("course_id", courseId);
        queryWrapper.eq("member_id", memberId);
        List<Order> orders = orderMapper.selectList(queryWrapper);
        // 校验结果集
        if (orders != null && orders.get(0).getStatus() == 1) {
            Map<String, Object> map = new HashMap<>(16);
            map.put("status", 1);
            return CommonResult.success("已支付", map);
        }
        return CommonResult.error("未支付");
    }

    @Override
    public CommonResult selectCourseOrder(OrderQuery orderQuery) {
        // 校验参数
        Assert.isRight(Check.isBlank(orderQuery), "订单查询参数不能为空");
        // 按条件查询
        QueryWrapper<Order> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq(Check.isNotBlank(orderQuery.getOrderNo()), "order_no", orderQuery.getOrderNo());
        queryWrapper.likeRight(Check.isNotBlank(orderQuery.getCourseTitle()), "course_title", orderQuery.getCourseTitle());
        queryWrapper.likeRight(Check.isNotBlank(orderQuery.getTeacherName()), "teacher_name", orderQuery.getTeacherName());
        queryWrapper.likeRight(Check.isNotBlank(orderQuery.getEmail()), "email", orderQuery.getEmail());
        queryWrapper.eq(orderQuery.getStatus() != null && (orderQuery.getStatus() == 1 || orderQuery.getStatus() == 0), "status", orderQuery.getStatus());
        // 按创建时间倒叙排序
        queryWrapper.orderByDesc("gmt_create");
        queryWrapper.select("id", "order_no", "course_title", "course_cover", "teacher_name", "nickname", "email", "total_fee", "pay_type", "status", "gmt_create");
        // 执行查询操作
        Page<Order> orderPage = new Page<>(orderQuery.getCurrent(), orderQuery.getLimit());
        Page<Order> page = orderMapper.selectPage(orderPage, queryWrapper);
        // 校验结果
        Assert.isRight(page.getRecords() == null, "查询订单信息失败");
        // 封装数据
        Map<String, Object> map = new HashMap<>(16);
        map.put("orders", page.getRecords());
        map.put("total", page.getTotal());
        return CommonResult.success("查询订单信息成功", map);
    }
}
